/* 
 * +-------- i博导 ibodao.com --------------------------------------------------------------
 */
$(document).ready(function () {
    if (navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE", "")) < 9) {

        var warmingText = "<div style='border-bottom:1px solid #e6cba6; background: #FEEFDA; text-align: center; clear: both; height: 40px; position: relative;'><div style='position: absolute; right: 5px; top: 8px;font-weight: bold;'>" +
                "<a href='#' onclick='javascript:this.parentNode.parentNode.style.display='none'; return false;'>" +
                "<i class='icon icon-guanbi' style='color:#666;'></i>" +
                "</a>" +
                "</div>" +
                "<div style='width: 880px; margin: 0 auto; text-align: left; padding: 0; overflow: hidden; color: black;'>" +
                "<div style='width: 25px; float: left;'>" +
                "<img src='/Public/home/images/low-if-waring.jpg' style='width:20px; padding-top:5px;' alt='Warning!'/>" +
                "</div>" +
                "<div style='padding:0 30px 0 5px; float: left;'>" +
                "<div style='font-size: 14px; margin-top: 9px;'>您使用的浏览器版本过低！ 强烈建议您使用现代浏览器！点击右侧图标下载任意一款新版浏览器。</div>" +
                "</div>" +
                "<div style='width: 24px; float: left; margin-right:20px; margin-top:7px;'>" +
                "<a href='http://www.firefox.com.cn/download/' target='_blank' title='火狐浏览器'>" +
                "<img src='/Public/home/images/firefox.png' style='width:100%; border: none;'/>" +
                "</a>" +
                "</div>" +
                "<div style='width: 24px; float: left; margin-right:20px; margin-top:7px;'>" +
                "<a href='http://rj.baidu.com/soft/detail/14744.html' target='_blank' title='谷歌浏览器'>" +
                "<img src='/Public/home/images/chrome.png' style='width:100%; border: none;'/>" +
                "</a>" +
                "</div>" +
                "<div style='width: 24px; float: left; margin-right:20px; margin-top:7px;'>" +
                "<a href='http://rj.baidu.com/soft/detail/14917.html' target='_blank' title='IE10'>" +
                "<img src='/Public/home/images/ie.png' style='width:100%; border: none;'/>" +
                "</a>" +
                "</div>" +
                "<div style='width: 24px; float: left; margin-right:20px; margin-top:7px;'>" +
                "<a href='http://rj.baidu.com/soft/detail/12966.html' target='_blank' title='safari浏览器'>" +
                "<img src='/Public/home/images/safari.png' style='width:100%; border: none;'/>" +
                "</a>" +
                "</div>" +
                "</div>" +
                "</div>";
        $("body").prepend(warmingText);
    }
});

$.ui = {
    load_index: 0,
    //错误
    error: function (str, sec, fun) {
        layer.close(this.load_index);
        sec = sec ? sec : 3500;
        layer.msg('<i class="icon icon-jinggao"></i> ' + str, {icon: 2, time: sec, offset: ['5px'], skin: 'layer-diy-error'}, fun);
    },
    //操作成功
    success: function (str, sec, fun) {
        layer.close(this.load_index);
        sec = sec ? sec : 3000;
        layer.msg('<span class="ui-span"><i class="icon icon-success"></i> ' + str + '</span>', {time: sec}, fun);
    },
    //操作成功
    tip: function (str, sec, fun) {
        layer.close(this.load_index);
        sec = sec ? sec : 3000;
        str = '<i class="icon icon-pinglun"></i> ' + str;
        layer.msg(str, {time: sec, offset: ['5px']}, fun);
    },
    //loading
    loading: function () {
        this.load_index = layer.load(1);
    },
    //closed loading
    closed: function () {
        layer.close(this.load_index);
    }

};

/*模态框加载页面*/
$.page = function (url, _width, _callback) {
    $.ui.loading();
    if ($('#J_modal_page').size() === 0) {
        $content = '<div class="modal-content"></div>';
        $html = '<div class="modal fade modal-ibodao" tabindex="-1" id="J_modal_page" style="display: block;"><div class="modal-dialog" role="document">' + $content + '</div></div>';
        $($html).appendTo('body');
    }
    if (typeof _width === 'string') {
        $('#J_modal_page>.modal-dialog').css('width', _width);
    } else if (typeof _width === 'function') {
        _callback = _width;
    }
    $.get(url, function (html) {
        if (typeof html === 'object') {
            if (html.url !== 'stop') {
                $('#J_modal_page').remove();
            }
            if (html.status === 0) {
                $.ui.error(html.info);
            } else {
                $.ui.success(html.info);
            }
            return false;
        }
        $('#J_modal_page .modal-content').html(html);
        layer.close($.ui.load_index);
        var page = $('#J_modal_page'),
                mh = page.height(),
                dialog = page.find('.modal-dialog'),
                oh = dialog.height(),
                top = oh > mh ? 0 : ((mh - oh) / 3);
        //p(top);
        dialog.css('top', top > 0 ? top : 0);
        dialog.find('.modal-body').css({maxHeight: mh - 220, overflowY: 'auto'});
        $('html,body').css({overflowY: 'hidden'});
        page.addClass('in').find('*[data-dismiss="modal"]').click(function () {
            $.page.close();
            $('html,body').css({overflowY: 'auto'});
        });
        if (typeof _callback === 'function') {
            //返回弹窗本身
            _callback(page);
        }
        //初始化表单
        //C.formSubmit();
        //拖动
        modal_drag();
    });
};
$.page.close = function () {
    $('#J_modal_page').removeClass('in');
    window.setTimeout(function () {
        $('#J_modal_page').remove();
        $('html,body').css({overflowY: 'auto'});
    }, 300);
};

//核心功能
C = window.C || [];
C.plugin = {};
//scheme://host:port/path?query#fragment
C.U = function (url, vars, suffix) {
    var _sub_u = {
        parse_url: function (url) {
            var parse = url.match(/^(?:([a-z]+):\/\/)?([\w-]+(?:\.[\w-]+)+)?(?::(\d+))?([\w-\/]+)?(?:\?((?:\w+=[^#&=\/]*)?(?:&\w+=[^#&=\/]*)*))?(?:#([\w-]+))?$/i);
            parse || $.ui.error('url格式不正确！');
            return{
                'scheme': parse[1],
                'host': parse[2],
                'port': parse[3],
                'path': parse[4],
                'query': parse[5],
                'fragment': parse[6]
            };
        },
        parse_str: function (str) {
            var value = str.split('&'), vars = {}, param;
            for (var val in value) {

                if (typeof value[val] == 'string') {
                    param = value[val].split('=');
                    vars[param[0]] = param[1];
                }
            }
            return vars;
        },
        parse_name: function (name, type) {
            if (type) {
                /*下划线转驼峰*/
                name.replace(/_([a-z])/g, function ($0, $1) {
                    return $1.toUpperCase();
                });
                /*首字母大写*/
                name.replace(/[a-z]/, function ($0) {
                    return $0.toUpperCase();
                });
            } else {
                /*大写字母转小写*/
                name = name.replace(/[A-Z]/g, function ($0) {
                    return '_' + $0.toLowerCase();
                });
                /*去掉首字符的下划线*/
                if (0 === name.indexOf('_')) {
                    name = name.substr(1);
                }
            }
            return name;
        }
    }
    var info = _sub_u.parse_url(url), path = [], param = {}, reg;
    /* 验证info */
    info.path || $.ui.error('url格式错误！');
    url = info.path;
    /* 组装URL */
    if (0 === url.indexOf('/')) { //路由模式
        this.MODEL[0] == 0 && $.ui.error("该URL模式不支持使用路由!(" + url + ")");
        /* 去掉右侧分割符 */
        if ("/" == url.substr(-1)) {
            url = url.substr(0, url.length - 1)
        }
        url = ('/' == this.DEEP) ? url.substr(1) : url.substr(1).replace(/\//g, this.DEEP);
        url = '/' + url;
    } else { //非路由模式
        /* 解析URL */
        path = url.split('/');
        path = [path.pop(), path.pop(), path.pop()].reverse();
        path[1] || $.error("ThinkPHP.U(" + url + ")没有指定控制器");
        if (path[0]) {
            param[this.VAR[0]] = this.MODEL[1] ? path[0].toLowerCase() : path[0];
        }
        param[this.VAR[1]] = this.MODEL[1] ? this.parse_name(path[1]) : path[1];
        param[this.VAR[2]] = path[2];
        url = '?' + $.param(param);
    }
    /* 解析参数 */
    if (typeof vars === 'string') {
        vars = _sub_u.parse_str(vars);
    } else if (!$.isPlainObject(vars)) {
        vars = {};
    }
    /* 解析URL自带的参数 */
    info.query && $.extend(vars, _sub_u.parse_str(info.query));

    if (vars) {
        url += '&' + $.param(vars);
    }
    if (0 != this.MODEL[0]) {
        url = url.replace('?' + (path[0] ? this.VAR[0] : this.VAR[1]) + '=', '/')
                .replace('&' + this.VAR[1] + '=', this.DEEP)
                .replace('&' + this.VAR[2] + '=', this.DEEP)
                .replace(/(\w+=&)|(&?\w+=$)/g, '')
                .replace(/[&=]/g, this.DEEP)
                .replace(/\/$/, '');
        /* 添加伪静态后缀 */
        if (false !== suffix) {
            suffix = suffix || this.MODEL[2].split('|')[0];
            if (suffix) {
                url += '.' + suffix;
            }
        }
    }
    url = this.APP + url;
    return url;
};
//创客贴
var chuangkitComplate = function(data){
    //p(data);
    if(data['thumb-urls']){
        urls = data['thumb-urls'];
        for(var i in urls){
            ckt.editor.execCommand('inserthtml', '<img alt="'+ data['design-id'] +'" id="'+ data['design-id'] +'" src="'+ urls[i] +'">');
        }
    }
};
var ckt = {
    init: function(){
        (function(d,s,a){var w=d.createElement(s),s=d.getElementsByTagName(s)[0];w.src=a;s.parentNode.insertBefore(w,s);})(document,'script','https://static.chuangkit.com/api/v4.js');
    },
    open: function(option, editor){
        var cktIframe = new ChuangkitIframe(option);
        cktIframe.openIframe();
        ckt.editor = editor;
    }
  };

//ajax返回的信息处理方法
C.ajax_return = function (res, _form) {
    $.ui.closed();
    if (typeof res.status === 'undfined') {
        res = JSON.parse(res);
    }
    if (res.status === 1 || res.status === 'true') {
        if(typeof res.info == 'string'){
           $.ui.success(res.info);
        }
        //如果存在全局提交回调 则执行回调方法并销毁
        if (res.url) {
            if (res.url !== 'stop') {
                window.setTimeout(function () {
                    if (res.url === -1) {
                        window.history.back();
                    } else if (res.url === 'reload') {
                        window.location.reload();
                    } else {
                        window.location.href = res.url;
                    }
                }, 1500);
            } else {
                var callback_fun;
                if (typeof _form === 'object') {
                    _form[0].reset();
                    _form.find('.btn').removeAttr('disabled');
                    callback_fun = _form.data('callback');
                }
                if (callback_fun) {
                    eval('callback_fun_do = ' + callback_fun + ';');
                    callback_fun_do(res);
                }
            }
        } else {
            //如果存在全局提交回调 则执行回调方法并销毁
            if (typeof $.submitCallback === 'function') {
                $.submitCallback(res);
                $.submitCallback = null;
                return;
            }
            window.setTimeout(function () {
                window.location.reload();
            }, 1500);
        }

    } else {
        if (res.type == 'login'){
            alert(res.info);
            _form.find('.btn').removeAttr('disabled');
            return false;

        }
        if (res.url !== 'login') {
            $.ui.error(res.info);
        }
        if (typeof _form === 'object') {
            _form.find('.btn').removeAttr('disabled');
        }
        if (res.data && res.data.focus) {
            $('input[name="' + res.data.focus + '"]').focus();
        }
        if (res.url === 'login') {
            layer.confirm(res.info, function () {
                window.location.href = C.U('/Member/login');
            });
            return false;
        }
        if (res.url && res.url !== 'stop') {
            window.setTimeout(function () {
                window.location.href = res.url;
            }, 2000);
        }
        if (typeof _form === 'object') {
            var callback_fun = _form.data('callback');
            if (callback_fun) {
                eval('callback_fun_do = ' + callback_fun + ';');
                callback_fun_do(res);
            }
        }
    }
};
//Form 提交处理
C.formSubmit = function () {

    $(document).on('submit', 'form[method="POST"][data-ajax="true"],form[method="post"][data-ajax="true"]', function () {
        var _form = $(this);
        var check_fun = _form.data('check');

        if (check_fun) {
            eval('check_result = ' + check_fun + ';');
        }
        if (typeof check_result === 'function' && check_result() === false) {
            return false;
        }
        $(this).find('.btn').attr('disabled', true);
        $.ui.loading();
        $.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(),
            dataType: 'json',
            success: function (res) {
                C.ajax_return(res, _form);
            }
        });
        return false;
    });
};
//AJAX请求
C.ajaxRequest = function () {

    //ajax加载页面
    $(document).on('click', '.J-ajax-page', function () {
        if ($(this).hasClass('disabled')) {
            return false;
        }
        var url = $(this).attr('data-href') || $(this).attr('href');
        var text = $(this).data('title');
        var width = $(this).data('width');
        var area = width ? (width + 'px') : '500px';
        $.page(url, area);
        return false;
    });

    //询问post提交
    $(document).on('click', '.J_ajax_confirm', function () {
        var _self = $(this),
            path = _self.attr('data-href') ||  _self.attr('href'),
                data = _self.data('params'),
                title = _self.data('msg') || _self.data('title');
        if (typeof data === 'undefined') {
            data = {r: Math.random()};
        }
        if (typeof title === 'undefined') {
            title = '您确定进行此操作吗？';
        }
        layer.confirm(title, function () {
            $.post(path, data, C.ajax_return);
        });
        return false;
    });


    //询问带内容post提交
    $(document).on('click', '.J_ajax_prompt', function () {
        var _self = $(this),
                data = _self.data('params'),
                title = _self.data('title');
        if (typeof data === 'undefined') {
            data = {r: Math.random()};
        }
        if (typeof title === 'undefined') {
            title = '请输入';
        }
        layer.prompt({
            title: title,
        }, function (value) {
            value = $.trim(value);
            if (value === '') {
                return false;
            }
            if (typeof data === 'object') {
                data.info = value;
            } else {
                data += '&info=' + value;
            }
            $.post(_self.attr('href'), data, C.ajax_return);
        });
        return false;
    });


    //GET
    $(document).on('click', '.J-ajax-get', function () {
        var url = $(this).attr('href') || $(this).attr('data-href');
        $.getJSON(url, C.ajax_return);
        return false;
    });

    //POST
    $(document).on('click', '.J-ajax-post', function () {
        $.post($(this).attr('href'), $(this).data('post'), C.ajax_return);
        return false;
    });
    
    //AJAX-DIV
    $(document).on('click', '.J-ajax-div', function(){
        var url = $(this).attr('href') || $(this).attr('data-href'),
        objbox = $(this).attr('data-ajaxdiv');
        $.ui.loading();
        $.get(url, {}, function(obj){
            $.ui.closed();
            if(typeof obj === 'object'){
                C.ajax_return();
                return false;
            }
            $(objbox).html(obj);
        });
        return false;
    });
};

//全局焦点事件
C.focus = function () {
    var width = $(window).width();
    //popover显示
    $('[data-toggle="popover"]').popover({
        trigger: 'manual',
        animation: false
    }).on("mouseenter", function () {
        $(this).popover("show");
    }).on("mouseleave", function () {
        var _this = this;
        setTimeout(function () {
            if (!$(".popover:hover").length) {
                $(_this).popover("hide");
            }
        }, 100);
    });
    $(document).on("mouseleave", ".popover", function () {
        $(this).remove();
    });

    //表单input删除框
    $('.form-control').on('keyup', function () {
        var _self = $(this);
        clean_input = _self.nextAll('.J_clean_input');
        if (_self.val() === '') {
            clean_input.hide();
        } else {
            clean_input.show();
        }
        clean_input.on('click', function () {
            _self.val('').focus();
            $(this).hide();
        });
    });
    //pc端
    if (width > 640) {
        //顶部导航划过切换
        $('.dropdown').hover(function () {
            $(this).addClass('open');
        }, function () {
            $(this).removeClass('open');
        });

        //顶部搜索
        $(document).on('click', function (e) {
            if ($(e.target).closest('.J_nav_search').size() === 0) {
                $('.J_nav_search .nav-search').fadeOut(function () {
                    $(this).removeClass('show');
                });
            }
        });
        $('.J_nav_search .c-search').click(function () {
            if ($('.J_nav_search .nav-search').hasClass('show')) {
                if ($('.J_keywords').val() !== '') {
                    $('.J_nav_search form').submit();
                } else {
                    $('.J_nav_search .nav-search').fadeOut(function () {
                        $(this).removeClass('show');
                    });
                }
            } else {
                $('.J_nav_search .nav-search').addClass('show');
            }
            $('.J_keywords').focus();
        });
        $('.J_search_type ul li').click(function () {
            $(this).siblings().removeClass('active');
            $(this).addClass('active');
            $(this).closest('.J_search_type').find('.type-text').text($(this).text());
            $(this).closest('.J_search_type').find('input[name="search_type"]').val($(this).data('type'));
            $(this).closest('ul').css('display', 'none');
            window.setTimeout(function () {
                $('.J_search_type ul').removeAttr('style');
            }, 200);
            $('.J_keywords').focus();
        });
    }

    //监控节点添加后的select
    $('body').bind('DOMNodeInserted', function (e) {
        $('body select.selectordie').each(function () {
            if ($(this).data('is_change_class') != 1) {
                $(this).data('is_change_class', 1).selectOrDie({size: 10});
            }
        });
    });

    //bootstrap 模态框位置
    $('*[data-toggle="modal"]').click(function () {
        var _self = $(this);
        var ob = $(_self.data('target')).removeClass('fade'),
                dialog = ob.find('.modal-dialog');
        window.setTimeout(function () {
            dialog.css('marginTop', 0).animate({
                top: ($(window).height() - dialog.height()) / 2.5
            }, 160);
        });
    });//bootstrap 模态框关闭后位置
    $('[aria-label="Close"]').click(function () {
        $(this).closest('.modal-dialog').css('top', 0);
    });

    //模态框兼容上传代码
    $(document).on('show.bs.modal', function () {
        window.setTimeout(function () {
            $(window).resize();
        }, 220);
    });
    
    var tip_index;
    //layer 提示层插件
    $(document).on('mouseenter', '[data-title]', function(){
        var html = $(this).attr('data-title');
        if(html){
            tip_index = layer.tips(html,$(this),{time: 30000});
        }
    });
    $(document).on('mouseleave', '[data-title]', function(){
        layer.close(tip_index);
    });
};

// 意见反馈、返回顶部、快捷摘录、...
C.plugin.rightTool = function (opt) {
    var cRtoolBoard = $('.c-right-tool');
    var _self = this;
    var defaults = {
        show: true, // 默认显示
        pos: {}, // 位置
        backTop: true, // 返回顶部
        feedBack: true, // 意见反馈
        quickExptSwitch: {},
        quickExptEle: {},
        quickExpt: {// 快捷摘录
            switch_: false, // 如果设置为false则不显示
            element: '' // 唯一id
        }
    };
    var options = $.extend(true, {}, defaults, opt);
    function RightTool() {
        this.show = options.show;
        this.pos = options.pos;
        this.backTop = options.backTop;
        this.feedBack = options.feedBack;

        this.quickExptSwitch = options.quickExpt.switch_;
        this.quickExptEle = options.quickExpt.element;


    }
    RightTool.prototype = {
        init: function () {
            if (!cRtoolBoard)
                return;
            if (this.show) {
                cRtoolBoard.removeClass('hide');
                cRtoolBoard.css(this.pos);
            }
            if (this.quickExptSwitch) {
                cRtoolBoard.prepend($('#' + this.quickExptEle));
                _self.quickExptInClass(this.quickExptEle, {right: 0, bottom: 0});
            }
            if (this.backTop) {
                this.backTopFn();
            }
            if (this.feedBack) {
                cRtoolBoard.find('.feed-back').removeClass('hide');
            }
            this.scroll();
        },
        scroll: function () {
            $(window).scroll(function () {
                var t = $(window).scrollTop();
                if (t > 400) {
                    cRtoolBoard.find('.back-top').show();
                    cRtoolBoard.addClass('effect');
                } else {
                    cRtoolBoard.find('.back-top').hide();
                    cRtoolBoard.removeClass('effect');
                }
            });
        },
        backTopFn: function () {
            cRtoolBoard.find('.back-top').on('click', function () {
                $('body ,html').animate({
                    scrollTop: 0
                }, 500);
            });
        },
        openQuickExpt: function (flag) {
            if (flag) {
                cRtoolBoard.addClass('open-effect');
                cRtoolBoard.prepend($('#' + this.quickExptEle));
                _self.quickExptInClass(this.quickExptEle, {right: 0, bottom: 0});
            }
        }
    };
    var right_tool = new RightTool();
    right_tool.init();
    return right_tool;

};

/* 快捷摘录到班级
 *  @param dom: 课程、测验、任务的type、id都放在dom上
 *  @param pos: 位置(right,bottom)  
 */
C.plugin.quickExptInClass = function (dom, pos) {
    var boardHtml = '<div class="qk-expt-board hide">' +
            '<div class="qk-expt-title"><span>请选择班级</span><span class="qk-expt-close">&times;</span></div>' +
            '<div class="qk-expt-content"></div>'+
            '<div class="beike_zhai">摘录到备课区 <span class="q-class-beike"></span></div>'+
            '</div>' +
            '<div class="qk-expt-btn"><span class="qk-i"><i class="icon icon-biji"></i><span>摘录</span></span><p>快&nbsp;捷</p><p>摘&nbsp;录</p></div>';
    // 任务摘录设置
    var taskHtml = '<div class="qk-exptask-board"><span class="qk-exptask-name">小组作业：</span>' +
            '<span><label><input type="radio" name="groupTask" value="1" />是</label>' +
            '<label><input type="radio" name="groupTask" value="0" checked="checked"/>否</label>' +
            '</span></div>' +
            '<div class="qk-exptask-board"><span class="qk-exptask-name">点评设置：</span>' +
            '<span><label><input type="radio" name="desginSet" value="0" />默认全站规则</label>' +
            '<label><input type="radio" name="desginSet" value="1" checked="checked"/>班级教师点评</label>' +
            '</span></div>';
    var defaultPos = {
        right: 60,
        bottom: 60
    };
    var initPos = $.extend({}, defaultPos, pos);
    var dom = $('#' + dom),
            id = dom.data('id'),
            type = dom.data('type'),
            reqUrl = dom.data('requrl'),
            detaUrl = dom.data('detaurl');
    dom.css({
        right: initPos.right + 'px',
        bottom: initPos.bottom + 'px'
    });
    dom.prepend(boardHtml);

    // prepend之后
    var showBtn = dom.find('.qk-expt-btn'),
            qkBoard = dom.find('.qk-expt-board'),
            qkCont = qkBoard.find('.qk-expt-content'),
            closeBtn = qkBoard.find('.qk-expt-close');

    // 显示班级
    dom.on('click', '.qk-expt-btn', function () {
        //查询是否已经摘录
        var excerpt = $('#q-id-keyexcerpt-excerpt');
        var data={
            'res_id':excerpt.data('id'),
            'res_type':excerpt.data('type'),
            //'category_id':category_id,
        };
        var excerpt_requrl= excerpt.data('requrl');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            async: false,
            url: excerpt_requrl,
            data: data,
            success: function (result) {
                if (result.status) {
                    if(parseInt(result.data.code)==2){
                        $('.beike_zhai').addClass("beike_zhai_done");
                        $('.q-class-beike').html('已摘录');
                    }
                }
            },
            error: function (err) {
                $.ui.error(err.toString());
            }
        });
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: reqUrl,
            data: {id: id, type: type},
            success: function (result) {
                if (result.status != 1) {
                    $.ui.error('你还没有班级，请先创建班级！');
                } else {
                    _setList(result.list);
                }
            },
            error: function (err) {
                $.ui.error(err.toString());
            }
        });


    });

    // 点击摘录到备课区
    dom.on('click','.beike_zhai',function(){
        var excerpt = $('#q-id-keyexcerpt-excerpt');
        var data={
            'res_id':excerpt.data('id'),
            'res_type':excerpt.data('type'),
            //'category_id':category_id,
        };
        var detaUrl= excerpt.data('detaurl');
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: detaUrl,
            data: data,
            success: function (result) {
                if (result.status) {
                    $('.beike_zhai').addClass("beike_zhai_done");
                    if(parseInt(result.data.code)==2){
                    }else if(parseInt(result.data.code)==1){
                        $.ui.success(result.msg);
                    }
                    $('.q-class-beike').html('已摘录');
                } else {
                    $.ui.error(result.msg);
                }
            },
            error: function (err) {
                $.ui.error(err.toString());
            }
        });
    });
    // 摘录到班级
    dom.on('click', 'a', function () {
        var a = $(this),
                p = a.parent(),
                isExpt = p.hasClass('is-expt'),
                classId = a.attr('data-clasid'),
                data = {};
        if (isExpt)
            return;
        if (type === 'task') {
            layer.open({
                type: 1,
                btn: ['确定', '取消'],
                title: '摘录设置',
                skin: 'qk-exptask-popup', //样式类名
                closeBtn: 1, //不显示关闭按钮
                shift: 0,
                shadeClose: true, //开启遮罩关闭
                content: taskHtml,
                btn1: function () {
                    var taskBoard = $(document).find('.qk-exptask-board'),
                            groupTask = taskBoard.find('[name="groupTask"]:checked').val(),
                            desginSet = taskBoard.find('[name="desginSet"]:checked').val();
                    data = {
                        classes_id: classId,
                        id: id,
                        type: type,
                        is_group: groupTask,
                        vay_comment: desginSet
                    };
                    layer.closeAll();
                    _exptIn(data, p);
                }
            });
        } else {
            data = {
                classes_id: classId,
                id: id,
                type: type
            };
            _exptIn(data, p);
        }
    });
    // 关闭
    closeBtn.on('click', function () {
        qkBoard.addClass('hide');
        showBtn.css('visibility', 'visible');
    });
    function _setList(list) {
        var itemHtml = '',
                isExpt = '',
                isExptHtml = '',
                isLoad = '',
                len = 0;
        qkCont.empty();
        $.each(list, function (k, v) {
            isExpt = v.is_excerpt == 1 ? 'is-expt' : '';
            isExptHtml = v.is_excerpt == 1 ? '<span>已摘录</span>' : '';
            isLoad = v.is_excerpt == 1 ? '' : '<i class="qk-liload hide"></i>';
            itemHtml += '<p class="' + isExpt + '">' + isLoad + '<a href="javascript:;" title="' + v.name + '" data-clasid="' + v.id + '">' + v.name + '</a>' + isExptHtml + '</p>';
        });
        qkCont.html(itemHtml);
        len = qkCont.find('p').length;
        qkCont.css({
            width: '230px',
            height: 32 * len + 'px'
        });
        showBtn.css('visibility', 'hidden');
        qkBoard.removeClass('hide');
    }

    function _exptIn(data, item) {
        var load = item.find('.qk-liload'),
                exTimer = null;
        $.ajax({
            type: 'POST',
            dataType: 'json',
            url: detaUrl,
            data: data,
            success: function (result) {
                if (result.status == 1) {
                    load.removeClass('hide');
                    exTimer = setTimeout(function () {
                        $.ui.success('摘录成功!');
                        item.addClass('is-expt');
                        item.append('<span>已摘录</span>');
                        load.addClass('hide');
                    }, 800);
                } else {
                    $.ui.error(result.msg);
                }
            },
            error: function (err) {
                $.ui.error(err.toString());
            }
        });
        clearTimeout(exTimer);
    }
};

/* cTooltip 提示框
 *  1：<a data-ctooltip="true" data-ctipmsg="发布新作业" data-ctiptype="right" href=""></a>
 *  2：$('a').Ctip( {opt} );
 */
C.plugin.tooltip = function () {
    var ctooltip,
            resiTimer = null,
            defaults = {
                pos: 'right', //位置 top left boottom right
                triggle: 'hover', //触发方式  !noWork
                offset: 0, //需要偏移的值  2个值{'top': x, 'left': y}
                className: '', //样式
                msg: '', //要提示的内容
                delay: 200, //延时 !noWork
                residenceTime: 0, //显示的时间
                destroy: false
            };

    var Ctooltip = function (ele, options) {
        var opt = $.extend(true, {}, defaults, options);
        this.pos = opt.pos;
        this.offset = opt.offset;
        this.triggle = opt.triggle;
        this.className = opt.className;
        this.delay = opt.delay;
        this.residenceTime = opt.residenceTime;
        this.destroy = opt.destroy;

        this.template = '<div class="c-z-tooltip ' + this.className + '"><div class="cz-tooltip-sign ' + this.pos + '"></div><div class="cz-tooltip-msg"></div></div>';
        this.$tip = '';
        this.posArr = ['top', 'right', 'bottom', 'left'];
        this.tipsPos = {};
        this.init(ele, opt);
    };
    Ctooltip.prototype = {
        init: function (ele, opt) {
            var _self = this;
            var msg = opt.msg || ele.attr('data-ctipmsg') || 'why so serious?';
            ele.on('mouseover mouseout', function (e) {
                var type = e.type;
                var winWid = $(window).outerWidth();
                if (winWid < 1490)
                    return;
                if (type == 'mouseover') {
                    $(_self.template).appendTo('body');
                    _self.$tip = $('body .c-z-tooltip');
                    _self.$tip.find('.cz-tooltip-msg').html(msg);
                    _self.setPos(ele);
                    if (_self.residenceTime) {
                        resiTimer = setTimeout(function () {
                            _self.removeTip();
                        }, _self.residenceTime);
                    }
                } else if (type == 'mouseout') {
                    _self.removeTip();
                    clearTimeout(resiTimer);
                }
            });
        },
        setPos: function (ele) {
            var _self = this;
            var eleWid = ele.outerWidth(),
                    eleHei = ele.outerHeight(),
                    offset = ele.offset(), // 相对窗口偏移值
                    top = offset.top,
                    left = offset.left;
            // tip中插入文字后的width height
            var tipWid = this.$tip.outerWidth(),
                    tipHei = this.$tip.outerHeight();
            if ($.inArray(this.pos, this.posArr) === -1)
                return false;
            switch (this.pos) {
                case 'top':
                    this.tipsPos.top = top - tipHei - 8;
                    this.tipsPos.left = left + (eleWid / 2 - tipWid / 2);
                    break;
                case 'right':
                    this.tipsPos.top = top + (eleHei / 2 - tipHei / 2);
                    this.tipsPos.left = left + eleWid + 8;
                    break;
                case 'bottom':
                    this.tipsPos.top = top + eleHei + 8;
                    this.tipsPos.left = left + (eleWid / 2 - tipWid / 2);
                    break;
                case 'left':
                    this.tipsPos.top = top + (eleHei / 2 - tipHei / 2);
                    this.tipsPos.left = left - tipWid - 8;
                    break;
            }
            if (this.offset) {
                this.tipsPos.top = this.tipsPos.top + (this.offset.top || 0);
                this.tipsPos.left = this.tipsPos.left + (this.offset.left || 0);
            }
            this.$tip.css(_self.tipsPos);
            this.$tip.addClass('in');
        },
        removeTip: function () {
            this.$tip.remove();
        }
    };

    function pluginCtip(ele, opt) {
        ctooltip = new Ctooltip(ele, opt);
    }
    $('body [data-ctooltip]').each(function () {
        var $this = $(this),
                isDo = $this.data('ctooltip'),
                options = {};
        if (!isDo)
            return;
        options.pos = $this.data('ctiptype');
        options.msg = $this.data('ctipmsg');
        pluginCtip($this, options);
    });
    $.fn.Ctip = function (options) {
        pluginCtip(this, options);
    };
};

/*
 * 勋章鼠标移入效果
 */
C.plugin.MouseDirection = function (element, opts) {
    var $element = $(element);
    //enter leave代表鼠标移入移出时的回调
    opts = $.extend({}, {
        enter: $.noop,
        leave: $.noop
    }, opts || {});
    var dirs = ['top', 'right', 'bottom', 'left'];
    var calculate = function (e) {
        var w = $element.outerWidth(),
                h = $element.outerHeight(),
                offset = $element.offset(),
                x = (e.pageX - offset.left - (w / 2)) * (w > h ? (h / w) : 1),
                y = (e.pageY - offset.top - (h / 2)) * (h > w ? (w / h) : 1);
        //鼠标方向判断
        return Math.round((((Math.atan2(y, x) * (180 / Math.PI)) + 180) / 90) + 3) % 4;
    };
    $element.on('mouseenter', function (e) {
        var r = calculate(e);
        opts.enter($element, dirs[r]);
    }).on('mouseleave', function (e) {
        var r = calculate(e);
        opts.leave($element, dirs[r]);
    });
};

//极验证初始化
var gee_init = function (obj, purpose) {
    $.ajax({
        url: C.U('/Home/Sinc/startCaptchaServlet', "random=" + Math.random()),
        type: "get",
        dataType: "json",
        success: function (data) {
            initGeetest({
                gt: data.gt,
                challenge: data.challenge,
                product: "popup",
                offline: !data.success
            }, function (captchaObj) {
                $.captcha_obj = captchaObj;
                captchaObj.bindOn(purpose);
                captchaObj.appendTo(obj);
            });
        }
    });
};

/**获取ajax数据**/
var get_page_info = function (obj, path, fun) {
    layer.load(1, {shade: [0.2, '#fff']});
    $.get(path, {}, function (html) {
        layer.closeAll('loading');
        $(obj).html(html);
        $(obj + ' .c-listpage a').unbind('click').click(function () {
            var path = $(this).attr('href');
            get_page_info(obj, path, fun);
            return false;
        });
        //回调
        if (typeof fun === 'function') {
            fun(path);
        }
    });
};

/***
 *
 * @param obj
 * 初始化验证码
 * zsb
 */
var yzm_init = function (obj, render, appkey, nc_type) {
    if (render == '')
        render = '#dom_id';
    if (nc_type == '')
        nc_type = 'register';
    var nc = new noCaptcha();
    var nc_appkey = appkey;
    var nc_scene = nc_type;
    var nc_token = [nc_appkey, (new Date()).getTime(), Math.random()].join(':');
    var nc_option = {
        renderTo: render,
        appkey: nc_appkey,
        scene: nc_scene,
        token: nc_token,
        callback: function (data) {// 校验成功回调
            $("#csessionid").val(data.csessionid);
            $("#sig").val(data.sig);
            $("#token").val(data.token);
            $("#scene").val(data.scene);
            if (data.value == 'pass' || data.value == 'bak_default' || data.value == 'ncc') {
                $("#code_status").val(1);
                if ($("#regname_status").val() == 1)
                    $(obj).removeAttr('disabled');
            }

        }
    };
    nc.init(nc_option);
};

//打印调试日志
var p = function (obj) {
    console.log(obj);
};
//检测是否为手机号码
var is_mobile_no = function (str) {
    return /^1[3|4|5|6|7|8|9]\d{9}$/.test(str);
};
//检测是否为email地址
var is_email = function (str) {
    return /^([a-zA-Z0-9]+[_|\_|\.|\-]?)*[a-zA-Z0-9]+@([a-zA-Z0-9]+[_|\_|\.]?)*[a-zA-Z0-9]+\.[a-zA-Z]{2,3}$/.test(str);
};
//检测是否为身份证号
var is_idcard = function (str) {
	return /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/i.test(str);
};
//检测邮编
var is_postcode = function (str) {
    return /^[0-9][0-9]{5}$/.test(str);
};
//字符串长度
var get_strlen = function (str) {
    if (str === null) {
        return 0;
    }
    if (typeof str !== "string") {
        str += "";
    }
    return str.replace(/[^\x00-\xff]/g, "01").length;
};
//modal绑定拖动
var modal_drag = function () {
    if ($('.modal-dialog').size() === 0) {
        return false;
    }
    $('.modal-dialog').draggable({
        delay: 100,
        opacity: 0.95,
        handle: '.modal-header'
    });
};

/* 设置表单的值 */
C.setValue = function (name, value) {
    var first = name.substr(0, 1), input, i = 0, val;
    if (value === "")
        return;
    if ("#" === first || "." === first) {
        input = $(name);
    } else {
        input = $("[name='" + name + "']");
    }

    if (input.eq(0).is(":radio")) { //单选按钮
        input.filter("[value='" + value + "']").each(function () {
            this.checked = true
        });
    } else if (input.eq(0).is(":checkbox")) { //复选框
        if (!$.isArray(value)) {
            val = new Array();
            val[0] = value;
        } else {
            val = value;
        }
        for (i = 0, len = val.length; i < len; i++) {
            input.filter("[value='" + val[i] + "']").each(function () {
                this.checked = true
            });
        }
    } else {  //其他表单选项直接设置值
        input.val(value);
        input.trigger('change');
    }
}

//全局执行z
$(function () {
    C.formSubmit();
    C.ajaxRequest();
    C.focus();
    modal_drag();
});

//处理windows IE9以下对于console.log的支持问题
window.console = window.console || (function(){ 
var c = {}; c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function(){}; 
return c; 
})();
